package com.bootdo.ocr.xfyun.dto;

import com.bootdo.ocr.OcrBaseResult;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Pattern;

public class XfYunOcrResult extends OcrBaseResult<Data> {

    public static String SUCCESS = "success";

    private String code;

    private String desc;

    private String sid;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public String getSid() {
        return sid;
    }

    public void setSid(String sid) {
        this.sid = sid;
    }

    @Override
    public String fetchGbCode(String pattern) {
        final Data data = getData();
        Set<String> gbCodeList = Sets.newHashSet();
        final List<BlockObj> block = data.getBlock();
        String patternVal = replacePatternBySpecialMap(pattern);
        for (int i = 0; i < block.size(); i++) {
            final BlockObj blockObj = block.get(i);
            final List<Word> lines = blockObj.getLine();

            for (Word line : lines) {
                final List<WordDetail> words = line.getWord();
                StringBuffer content = new StringBuffer();
                words.forEach(wordInfo -> content.append(wordInfo.getContent()));
                String code = matchWord(content.toString(), Pattern.compile(patternVal));
                code = filterUpdateCode(code);
                if (StringUtils.isNotEmpty(code)) {
                    gbCodeList.add(code);
                }
            }

        }
        Optional<String> optional = gbCodeList
                .stream()
                .max((o1, o2) ->
                {
                    if (o1.length() > o2.length()) {
                        return  1;
                    } else if(o1.length() < o2.length()) {
                        return -1;
                    }
                    return o1.compareTo(o2);
                });
        return  optional.isPresent() ? optional.get() : null;
    }

}
